import sys
import os

from spass.core.error import error

__spass_root = os.getenv('SPASS_ROOT')

__plugins_commands_root = __spass_root + '/plugins/commands/'
__plugins_commands_main_exe = 'main'
__plugins_commands_main_file = __plugins_commands_main_exe + '.py'

def _test_command_path(command_name):
    command_path = __plugins_commands_root + command_name +\
        '/' + __plugins_commands_main_file
    
    return (os.access(command_path, os.R_OK) and
            os.path.isfile(command_path) and
            not command_name[0] == '.')

def plugin_init():
    if __spass_root == None:
        error('not.root', [])
        return False
    return True
    
def is_plugin(command_name):
    return _test_command_path(command_name)

def run_plugin(command_name, options):
    name = 'spass.plugins.commands.'+command_name+'.main'
    __import__(name)
    command = sys.modules[name]
    return command.run(options)

def list_plugins(argv=None):
    count = 0
    print 'Spass plugins : '
    for plugin in os.listdir(__plugins_commands_root):
        if _test_command_path(plugin):
            print "\t- " + plugin
            count = count + 1
    if count == 0:
        error('no.plugin', [])

def plugin(argv):
    list_plugins(argv)
    return 0
